/**
 * 安全替换div内容并处理资源
 * @param {string} divId - 要替换内容的div的ID
 * @param {string} newHtml - 完整的HTML内容
 */
async function replaceDivContent(divId, newHtml) {
  const targetDiv = document.getElementById(divId);
  if (!targetDiv) {
    console.error(`找不到ID为"${divId}"的元素`);
    return;
  }

  // 1. 清空目标div的所有内容
  targetDiv.innerHTML = '';

  // 2. 使用DOMParser解析新HTML
  const parser = new DOMParser();
  const newDoc = parser.parseFromString(newHtml, 'text/html');

  // 3. 提取新内容中的body部分(不包括script)
  const bodyNodes = Array.from(newDoc.body.childNodes);
  const newContent = bodyNodes.filter(node => node.nodeName !== 'SCRIPT');

  // 4. 提取需要单独处理的资源
  const styles = Array.from(newDoc.querySelectorAll('style'));
  const links = Array.from(newDoc.querySelectorAll('link[rel="stylesheet"]'));
  const scripts = Array.from(newDoc.querySelectorAll('script'));

  // 5. 先插入非脚本内容
  targetDiv.append(...newContent);

  // 6. 处理样式(先加载CSS)
  await loadResources('styles', styles, links);

  // 7. 处理脚本(后加载JS)
  await loadResources('scripts', scripts);
}

/**
 * 加载资源(样式或脚本)
 */
async function loadResources(type, elements, links = []) {
  const head = document.head;

  if (type === 'styles') {
    // 处理内联样式
    for (const style of elements) {
      const newStyle = document.createElement('style');
      newStyle.textContent = style.textContent;
      head.appendChild(newStyle);
    }

    // 处理外部样式表
    for (const link of links) {
      await new Promise(resolve => {
        const newLink = document.createElement('link');
        newLink.rel = 'stylesheet';
        newLink.href = link.href;
        newLink.onload = resolve;
        newLink.onerror = () => {
          console.error(`样式表加载失败: ${link.href}`);
          resolve();
        };
        head.appendChild(newLink);
      });
    }
  } 
  else if (type === 'scripts') {
    // 处理脚本
    for (const script of elements) {
      await new Promise(resolve => {
        const newScript = document.createElement('script');
        
        // 复制所有属性
        Array.from(script.attributes).forEach(attr => {
          newScript.setAttribute(attr.name, attr.value);
        });

        // 内联脚本
        if (!script.src && script.textContent) {
          newScript.text = script.textContent;
          head.appendChild(newScript).remove();
          resolve();
          return;
        }

        // 外部脚本
        if (script.src) {
          newScript.onload = resolve;
          newScript.onerror = () => {
            console.error(`脚本加载失败: ${script.src}`);
            resolve();
          };
          head.appendChild(newScript);
        } else {
          resolve();
        }
      });
    }
  }
}

// 使用示例
/*
replaceDivContent('content-container', `
<!DOCTYPE html>
<html>
<head>
  <style>
    .new-style { color: blue; }
  </style>
  <link rel="stylesheet" href="new-styles.css">
</head>
<body>
  <div class="new-style">新内容</div>
  <script src="new-script.js"></script>
  <script>
    console.log('新内联脚本执行');
  </script>
</body>
</html>
`);
*/